﻿//-----------------------------------------------------------------------------------
// Detailed Extraction Rule Template version 1.0
//-----------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Globalization;
using Microsoft.VisualStudio.TestTools.WebTesting;
using System.Xml;
using System.Xml.XPath;

namespace WebServicesTesting.Automation.WebTest.ExtractionRules
{
    [System.ComponentModel.DisplayName("InvalidDataExtraction")]
    [System.ComponentModel.Description("TODO: Add a more detailed description of InvalidDataExtraction extraction rule.")]
    public class InvalidDataExtraction : ExtractionRule
    {
        #region Constructors
        /// <summary>
        /// standard constructor
        /// </summary>
        public InvalidDataExtraction() { }
        #endregion

        #region Properties
        /// <summary>
        /// If True, the extraction rule fails if not found.
        /// </summary>
        
        
        [System.ComponentModel.Description("If True, the extraction rule fails if not found.")]
        [System.ComponentModel.DefaultValue(true)]
        private string Tag;
        [Description("XPath Expression to evaluate against the response")]
        public string XPathExpression
        {
            get { return Tag; }
            set { Tag = value; }
        }

        /// <summary>
        /// Contains value that was extracted.
        /// </summary>
        

        /*
         * Public properties on the class will be surfaced to the user in the VS UI.
         * Only string, int, and bool types are allowed.
         */

        /*
            /// <summary>
            /// Sample string property
            /// </summary>
            private string m_myStringProperty;
            [System.ComponentModel.DisplayName("My String Property")]
            [System.ComponentModel.Description("Enter a long description for this property.")]
            [System.ComponentModel.DefaultValue("MyString")]
            public string MyStringProperty
            {
                get { return m_myStringProperty; }
                set { m_myStringProperty = value; }
            }
        */

        #endregion // Properties

        #region Utility Functions
        /// <summary>
        /// A sample utility function that performs the actual work of extracting values. 
        /// This demonstrates the best practice of moving most of the code out into 
        /// it's own function so you can test it from a unit test.
        /// </summary>
        /// <returns>true - value found, false - value not found, reason contains more details</returns>
        public bool Extract(string document)
        {
            Debug.Assert(document != null);
            // TODO:  Implement your extraction code here
            throw (new NotImplementedException("ExtractionRule1:MyExtractionFunction not implemented !"));

            // m_extractedValue = "Value found";
            // m_message = "Additional information regarding success/failure of function";
            // return true; // true if found, false if not found
        }
        #endregion

        #region Extract Method
        /// <summary>
        /// The Extract method.  The parameter e contains the Web test context.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void Extract(object sender, ExtractionEventArgs e)
        {

            try
            {
                XmlDocument doc = e.Response.XmlDocument;

                XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
                nsMgr.AddNamespace("s", doc.DocumentElement.NamespaceURI);
                XPathNavigator nav = doc.CreateNavigator();
                XmlNode responseBody = doc.SelectSingleNode("//s:Body", nsMgr);
                string responseNS = responseBody.FirstChild.Attributes[0].Value;
                if (responseNS != null && responseNS.Length > 0)
                {
                    nsMgr.AddNamespace("response", responseNS);
                }
                XPathNodeIterator iterator = nav.Evaluate(Tag, nsMgr) as XPathNodeIterator;
                if (iterator.Count > 0)
                {
                    string value = string.Empty;
                    while (iterator.MoveNext())
                    {
                        value += iterator.Current.Value;
                    }

                    e.Success = true;
                    e.WebTest.Context.Add(this.ContextParameterName, value);
                }
                else
                {
                    e.WebTest.Context.Add(this.ContextParameterName, "No Response From Service-Invalid Data");
                    e.Request.Outcome = Outcome.Fail;
                }
            }
            catch (Exception ex)
            {
                e.Message = String.Format(CultureInfo.CurrentCulture, "{0}[{1}] Exception: {2}", "ExtractionRule1", this.ContextParameterName, ex.Message.ToString());
                e.Success = false;
            }
        }
            
        #endregion
    }
}
